<script setup>
import {ref,watch,onMounted} from 'vue';
import { queryPageApi,addClazzApi,queryByIdApi,updateApi,deleteApi} from '@/api/clazz';
import { listApi as queryEmpListApi } from '@/api/emp';
import { ElMessage ,ElMessageBox} from 'element-plus';

//条件查询表单
const clazzQueryFrom=ref({
  name: '',
  date:[],
  begin:'',
  end:''
})
//班级集合
const calzzList=ref([]);

// 分页条
const currentPage = ref(1)
const pageSize = ref(10)
const background = ref(true)
const total=ref(0);

// 对话框显示、隐藏
const dialogFormVisible = ref(false)

//对话框标题
const dialogTitle=ref('新增班级')

//对话框表单
const clazzForm = ref({
  name: '',
  room: '',
  beginDate: '',
  endDate: '',
  masterId: '',
  subject: ''
})

//学科数据
const subjectList=ref([{name : 'java',value : 1},{name : '前端',value : 2},{name : '大数据',value : 3},{name : 'Python',value : 4},{name : 'Go',value : 5},{name : '嵌入式',value : 6}])


//员工数据
const empList=ref([]);

//表单引用
const clazzFromRef=ref();

//侦听
watch(()=>clazzQueryFrom.value.date,(newVal,oldVal)=>{
  if(newVal.length==2){
    clazzQueryFrom.value.begin=newVal[0];
    clazzQueryFrom.value.end=newVal[1];
  }else{
    clazzQueryFrom.value.begin='';
    clazzQueryFrom.value.end='';
  }
})



//查询
const search= async()=>{
 const result=await queryPageApi(clazzQueryFrom.value.name,clazzQueryFrom.value.begin,clazzQueryFrom.value.end,currentPage.value,pageSize.value);
 if(result.code){
  calzzList.value=result.data.rows;
  total.value=result.data.total;
 }
}

//查询全部员工
const getAllEmps=async()=>{
  const result=await queryEmpListApi();
  if (result.data && result.data.length>0) {
    empList.value=result.data;
  }
}

//钩子函数
onMounted(()=>{
  getAllEmps();
  search();
})

//清除搜索栏数据
const clear=()=>{
  clazzQueryFrom.value={ name: '', date:[], begin:'',end:''}
  search();
}

// 每页展示记录数变化
const handleSizeChange = (val) => {
  search();
}

// 页码变化时触发
const handleCurrentChange = (val) => {
  search();
}

//打开对话框
const addClazz=()=>{
  dialogFormVisible.value=true;
  dialogTitle.value='新增班级';
  clazzForm.value={name: '',
  room: '',
  beginDate: '',
  endDate: '',
  masterId: '',
  subject: ''}

  if(clazzFromRef.value){
    clazzFromRef.value.resetFields();
  }
}

//保存数据
const save= async()=>{
  if(!clazzFromRef.value) return;
  await clazzFromRef.value.validate(async (valid)=>{
    if (valid) {
      let result;
      if (clazzForm.value.id) {
        result=await updateApi(clazzForm.value);
      }else{
        result=await addClazzApi(clazzForm.value);
      }
      if(result.code){
        ElMessage.success(result.msg);
        dialogFormVisible.value=false;
        search();
      }else{
        ElMessage.error(result.msg);
      }
    }else{
      ElMessage.error("表单校验失败");
    }
  })

}

//表单校验规则
const rules = ref({
  name: [
    { required: true, message: '请输入班级名称', trigger: 'blur' },
    { min: 2, max: 10, message: '班级名称长度应在2到10个字符之间', trigger: 'blur' }
  ],
  beginDate: [
    { required: true, message: '请选择日期', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择日期', trigger: 'blur'  }
  ],
  subject: [
    { required: true, message: '请选择学科', trigger: 'blur'  }
  ]
});

//根据ID查询数据
const Edit=async (id)=>{
  const result=await queryByIdApi(id);
  if(result.code){
    clazzForm.value=result.data;
    dialogFormVisible.value=true;  
  }
}

//删除员工
const delClazz= async(id)=>{
  ElMessageBox.confirm('确认删除数据吗?','提示',{confirmButtonText: '确认',cancelButtonText: '取消',type: 'error'}
  ).then(async() => {
    const result=await deleteApi(id);
  if(result.code){
    ElMessage.success(result.msg);
    search();
  }else{
    ElMessage.error(result.msg);
  }
    }).catch(() => {
      ElMessage.info("取消删除")
    }) 
}
</script>

<template>
 <h1>班级管理</h1> 
 <div class="container">
    <!-- 搜索栏 -->
    <el-form :inline="true" :model="clazzQueryFrom" class="demo-form-inline">
    <el-form-item label="班级名称">
      <el-input v-model="clazzQueryFrom.name" placeholder="请输入班级名称" clearable />
</el-form-item>
    <el-form-item label="结课时间">
      <el-date-picker
        v-model="clazzQueryFrom.date"
        type="daterange"
        range-separator="到"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="info" @click="clear">清空</el-button>
    </el-form-item>
  </el-form>
  </div>
  <!-- 按钮 -->
   <div class="container">
    <el-button type="primary" @click="addClazz">+ 新增班级</el-button>
   </div><br>

   <!-- 展示表格 -->
    <div class="container">
      <el-table :data="calzzList" border style="width: 100%" >
      <el-table-column type="index" width="50" label="序号" />
      <el-table-column prop="name" label="班级名称" width="120" align="center"/>
      <el-table-column prop="room"  label="班级教师" width="120" align="center" />
      <el-table-column prop="masterName"  label="班主任" width="120" align="center"/>
      <el-table-column prop="beginDate" label="开课时间" width="120" align="center"/>
      <el-table-column prop="endDate" label="结课时间" width="120" align="center" />
      <el-table-column prop="status" label="状态" width="120" align="center"/>
      <el-table-column prop="updateTime" label="最后修改时间" width="200" align="center"/>
      <el-table-column  label="操作" align="center">
        <template #default="scope">
            <el-button size="small" @click="Edit(scope.row.id)">修改</el-button>
            <el-button size="small" type="danger" @click="delClazz(scope.row.id)">删除</el-button>
          </template>
      </el-table-column>
    </el-table>
   </div><br>

<!-- 分页条 -->
<div class="container">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5,10, 20, 30, 50]"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <!-- 新增修改对话框 -->
  <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500">
    <el-form :model="clazzForm" :rules="rules" ref="clazzFromRef">
      <el-form-item label="班级名称" :label-width="formLabelWidth" prop="name">
        <el-input v-model="clazzForm.name" autocomplete="off" placeholder="请输入班级名称" />
      </el-form-item>
      <el-form-item label="班级教室" :label-width="formLabelWidth">
        <el-input v-model="clazzForm.room" autocomplete="off" placeholder="请输入班级教师" />
      </el-form-item>
      <el-form-item label="开课时间" :label-width="formLabelWidth" prop="beginDate">
        <el-date-picker
        v-model="clazzForm.beginDate"
        type="date"
        placeholder="请选择开课时间"
        value-format="YYYY-MM-DD"
      />
      </el-form-item>

      <el-form-item label="结课时间" :label-width="formLabelWidth" prop="endDate">
        <el-date-picker
        v-model="clazzForm.endDate"
        type="date"
        placeholder="请选择结课时间"
        value-format="YYYY-MM-DD"
      />
      </el-form-item>
 
      <el-form-item label="班主任" :label-width="formLabelWidth">
        <el-select v-model="clazzForm.masterId" placeholder="请选择班主任">
          <el-option v-for="emp in empList" :key="emp.id" :label="emp.name" :value="emp.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="学科" :label-width="formLabelWidth" prop="subject">
        <el-select v-model="clazzForm.subject" placeholder="请选择学科">
          <el-option v-for="sub in subjectList" :key="sub.name"  :label="sub.name" :value="sub.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<style scoped>
</style>